<script setup>
import {init,chunk,merge,status} from '@/utils/api/fileUpoad.js'

const SIZE = 1024 * 1024 * 5
const files = ref([])
const data = ref([])
const fileUpload = ref(null)
const handleUpload = () =>{
    fileUpload.value.click()
}

const handleFileChange = async (e) =>{
    const [file] = e.target.files;
    if (!file) return;
    files.value = file
    const fileChunkList = createFileChunk(file,SIZE);
    data.value = fileChunkList.map(({file},index)=>({
        chunk:file,
        hase:file.name+"_"+index,
        index
    }))
    let obj = {
        filename:file.name,
        fileSize:file.size,
        totalChunks:data.value.length
    }
    const res = await init(obj)
    console.log(res);
    if(res.success){
        await uploadChunk(res.data.fileId)
    }
    
    // 
}
// 生成切片文件
const  createFileChunk = (file, size) => {
    const chunkList = [];
    let cur = 0;
    while (cur < file.size) {
        chunkList.push({ file: file.slice(cur, cur + size) });
        cur += size;
    }
    return chunkList;
};
// 上传切片
const uploadChunk = async (file_Id) => {
    let fileId = file_Id;
    const requestList = data.value.map(({chunk,hash,index})=>{
        const formData = new FormData();
        formData.append("chunk", chunk);
        formData.append("chunkIndex", index);
        formData.append("fileId", fileId);
        return formData;
    }).map((formData)=>{
        return chunk(formData)
    })
    await Promise.all(requestList)
    await mergeRequest(fileId);
};
// 合并切片
const mergeRequest = async (fileId) =>{
    await merge({fileId})
}
// 单个文件上传进度
const createProgressHandler = item => {
    return e => {
        item.percentage = Math.floor((e.loaded / e.total) * 100);
    };
}
// 总上传进度
const uploadPercentage = computed(() => {
    if (!data.value || !data.value.length) return 0;
    const percentages = data.value.map(item => item.percentage);
    const total = percentages.reduce((t, c) => c + t, 0);
    return Math.floor(total / percentages.length);
});
</script>

<template>
    <h2>大文件上传</h2>
    <div>
        <input ref="fileUpload" type="file" class="files" @change="handleFileChange">
        <!-- <el-button @click="handleUpload">上传</el-button> -->

        <el-button @click="handleUpload">开始上传</el-button>
    </div>
</template>

<style lang="scss" scoped>

</style>